/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package easemob.chatuidemo.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.wolfalpha.utron.R;
import com.wolfalpha.utron.activity.TlzDetailActivity;
import com.wolfalpha.utron.activity.UserInfoActivity;
import com.wolfalpha.utron.activity.base.BaseNormalActivity;
import com.wolfalpha.utron.adapter.ItemSearchGroupAdapter;
import com.wolfalpha.utron.adapter.ItemSearchUserAdapter;
import com.wolfalpha.utron.bean.Jlq;
import com.wolfalpha.utron.bean.UserInfo2;
import com.wolfalpha.utron.service.impl.FriendsServiceImpl;
import com.wolfalpha.utron.ui.UIHelper;
import com.wolfalpha.utron.utils.ThreadPoolUtils;

import java.util.List;

/**
 * 搜索并添加新的好友
 */
public class AddContactActivity extends BaseNormalActivity {
    private EditText editText;
    private LinearLayout searchedUserLayout;
    private TextView nameText, mTextView;
    private Button searchBtn;
    private ImageView avatar;
    private InputMethodManager inputMethodManager;
    private String toAddUsername;
    private ProgressDialog progressDialog;

    private ListView lvResult;

    private ItemSearchUserAdapter fAdapter;
    private ItemSearchGroupAdapter qunAdapter;

    boolean isQun = false;
    private List<UserInfo2> info2s = null;
    private List<Jlq> quns = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getIntent().getExtras();
        if (bundle != null && bundle.containsKey("qun")) {
            //为搜索群
            isQun = true;
        }

        setContentView(R.layout.activity_partner_add_contact);

        if (isQun) {
            setTvTitle("搜索群");
        } else {
            setTvTitle("搜索好友");
        }

        editText = (EditText) findViewById(R.id.edit_note);
//        searchedUserLayout = (LinearLayout) findViewById(R.id.ll_user);
//        nameText = (TextView) findViewById(R.id.name);
//        avatar = (ImageView) findViewById(R.id.avatar);
        searchBtn = (Button) findViewById(R.id.btn_add_contact_search);
        lvResult = (ListView) findViewById(R.id.lv_search_result);

        if (isQun) {
            lvResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (isQun && quns != null) {
                        Bundle bundle = new Bundle();
                        bundle.putInt("id", quns.get(position).getId());
                        bundle.putString("name", quns.get(position).getName());
                        bundle.putString("qun", "yes");
                        UIHelper.showActivity(AddContactActivity.this, TlzDetailActivity.class, bundle);
                        finish();
                    }
                }
            });
        } else {
            lvResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (!isQun && info2s != null) {
                        Bundle bundle = new Bundle();
                        bundle.putInt("userId", info2s.get(position).getUser_id());
                        UIHelper.showActivity(AddContactActivity.this, UserInfoActivity.class, bundle);
                        finish();
                    }
                }
            });
        }

        searchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchContact();
            }
        });
    }

    /**
     * 查找contact
     */
    public void searchContact() {
        final String name = editText.getText().toString();
        toAddUsername = name;
        if (TextUtils.isEmpty(name)) {
            UIHelper.ToastMessage(AddContactActivity.this, "关键字不能为空");
            return;
        }
        // TODO 从服务器获取此contact,如果不存在提示不存在此用户
        //服务器存在此用户，显示此用户和添加按钮
//        searchedUserLayout.setVisibility(View.VISIBLE);
//        nameText.setText(toAddUsername);

        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                if (!isQun) {
                    info2s = new FriendsServiceImpl().searchUser(toAddUsername);
                    if (info2s != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                fAdapter = new ItemSearchUserAdapter(AddContactActivity.this, info2s);
                                lvResult.setAdapter(fAdapter);
                                lvResult.invalidate();
                            }
                        });
                    }
                } else {
                    quns = new FriendsServiceImpl().searchJlq(toAddUsername);
                    if (quns != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                qunAdapter = new ItemSearchGroupAdapter(AddContactActivity.this, quns);
                                lvResult.setAdapter(qunAdapter);
                                lvResult.invalidate();
                            }
                        });
                    }
                }
            }
        });
    }

//    private String temp = "请求加好友";
//
//    /**
//     * 添加contact
//     *
//     * @param view
//     */
//    public void addContact(View view) {
//        if (AppContext.getInstance().getUserInfo().getNickname().equals(nameText.getText().toString())) {
//            String str = "不能添加自己";
////            startActivity(new Intent(this, AlertDialog.class).putExtra("msg", str));
//            UIHelper.ToastMessage(AddContactActivity.this, str);
//            return;
//        }
//
//        if (((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList() != null && ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList().containsKey(nameText.getText().toString())) {
//            //提示已在好友列表中，无需添加
//            if (EMContactManager.getInstance().getBlackListUsernames().contains(nameText.getText().toString())) {
//                UIHelper.ToastMessage(AddContactActivity.this, "此用户已经是你的好友");
//                return;
//            }
//            UIHelper.ToastMessage(AddContactActivity.this, "此用户已经是你的好友");
//            return;
//        }
//
//        final EditAlertDialog editAlertDialog = new EditAlertDialog(AddContactActivity.this);
//        editAlertDialog.setHint("请验证身份");
//        editAlertDialog.setOnFinishedListener(new EditAlertDialog.OnFinishedListener() {
//            @Override
//            public void finish(String input) {
//                if (!TextUtils.isEmpty(input)) {
//                    temp = input;
//
//                    final ProgressDialog progressDialog = new ProgressDialog(AddContactActivity.this);
//                    String stri = "已发送";
//                    progressDialog.setMessage(stri);
//                    progressDialog.setCanceledOnTouchOutside(false);
//                    progressDialog.show();
//
//                    new Thread(new Runnable() {
//                        public void run() {
//
//                            try {
//                                EMContactManager.getInstance().addContact(nameText.getText().toString(), temp);
//                                runOnUiThread(new Runnable() {
//                                    public void run() {
//                                        progressDialog.dismiss();
//                                        String s1 = "发送成功";
//                                        UIHelper.ToastMessage(AddContactActivity.this, s1);
//                                    }
//                                });
//                            } catch (final Exception e) {
//                                e.printStackTrace();
//                                runOnUiThread(new Runnable() {
//                                    public void run() {
//                                        progressDialog.dismiss();
//                                        UIHelper.ToastMessage(AddContactActivity.this, "发送失败");
//                                    }
//                                });
//                            }
//                        }
//                    }).start();
//                }
//            }
//        });
//
//    }
}
